/*
*  LLStringUtils.h  
*  LID Library
*
*  Created by Alexander Trutchenko on 11/01/12.
*  Copyright 2012 League of Independent Developers. All rights reserved.
*
*/

#include "lid_lib/src/strings_and_localization/LLStringUtils.h"

#include "lid_lib/src/strings_and_localization/externals/ConvertUTF.h"
#include "lid_lib/src/service/LLAssert.h"


using namespace std;

namespace lidlib
{
  

wstring utf8_string_to_utf16_wstring(const std::string& utf8string)
{
    size_t widesize = utf8string.length();
    wstring resultstring;
    resultstring.resize(widesize, L'\0');
    const UTF8* sourcestart = reinterpret_cast<const UTF8*>(utf8string.c_str());
    const UTF8* sourceend = sourcestart + widesize;
    ConversionResult res = sourceIllegal;
    if (sizeof(wchar_t) == 2)
    {
        UTF16* targetstart = reinterpret_cast<UTF16*>(&resultstring[0]);
        UTF16* targetend = targetstart + widesize;
        res = ConvertUTF8toUTF16(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
    }
    else if (sizeof(wchar_t) == 4)
    {
        UTF32* targetstart = reinterpret_cast<UTF32*>(&resultstring[0]);
        UTF32* targetend = targetstart + widesize;
        res = ConvertUTF8toUTF32(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
    }
    LLAssert(res == conversionOK, "utf8_string_to_utf16_wstring: wrong convertion!!!");
    return resultstring;
}

std::string utf16_wstring_to_utf8_string(const wstring& widestring)
{
    size_t widesize = widestring.length();
//    size_t utf8size = sizeof(wchar_t) * widesize;
    size_t utf8size = widesize;
    std::string resultstring;
    resultstring.resize(utf8size, '\0');
    ConversionResult res = sourceIllegal;
    if (sizeof(wchar_t) == 2)
    {
        const UTF16* sourcestart = reinterpret_cast<const UTF16*>(widestring.c_str());
        const UTF16* sourceend = sourcestart + widesize;
        UTF8* targetstart = reinterpret_cast<UTF8*>(&resultstring[0]);
        UTF8* targetend = targetstart + utf8size;
        res = ConvertUTF16toUTF8(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
    }
    else if (sizeof(wchar_t) == 4)
    {
        const UTF32* sourcestart = reinterpret_cast<const UTF32*>(widestring.c_str());
        const UTF32* sourceend = sourcestart + widesize;
        UTF8* targetstart = reinterpret_cast<UTF8*>(&resultstring[0]);
        UTF8* targetend = targetstart + utf8size;
        res = ConvertUTF32toUTF8(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
    }

    LLAssert(res == conversionOK, "utf16_wstring_to_utf8_string: wrong convertion!!!");
    return resultstring;
}

} //end namespace lidlib
